package com.apes.scm.masterdata.frame.service;

import com.alibaba.fastjson.JSONObject;
import com.apes.framework.api.DomainService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.express.FuncAlias;
import com.apes.framework.rop.converter.DateUtils;
import com.apes.framework.util.EventUtil;
import com.apes.scm.masterdata.frame.model.*;
import com.apes.scm.masterdata.frame.repository.DeptRepository;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.*;


/**
 * 功能：部门信息
 *
 * @author HuJianlin
 * @create 2018-03-17 16:35
 */
@Service("deptService")
public class DeptService extends DomainService {

    @Autowired
    public DeptRepository deptRepository;
    @Autowired
    StoreRepository storeRepository;

    public Dept save(SimpleRequest request) {
        Dept dept = request.getO(Dept.class);
        dept.setId(dept.obtainDeptId(dept));
        dept = deptRepository.saveAndFlush(dept);
        synBMXXorDDXX(dept);
        return dept;

    }

    public Dept update(SimpleRequest request) {
        Dept dept = request.getO(Dept.class);
        dept = deptRepository.saveAndFlush(dept);
//        synBMXXorDDXX(dept);
        return dept;
    }

    public Page<Store> queryAllSpaceDept(SimpleRequest simpleRequest){
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        Page<Store> all = storeRepository.findAll(JpaDsl.toCriteriaByEq("containSpace", true), PageRequest.of(simpleRequest.get("page"), simpleRequest.get("size"), sort));

        return all;
    }

    public Page<Store> queryAllSpaceDeptLike(SimpleRequest request){
        Sort sort = new Sort(Sort.Direction.DESC, "id");
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("key");
        return storeRepository.findLikeName2(id, PageRequest.of(request.get("page"), request.get("size"), sort));
    }

    public void synBMXXorDDXX(Dept dept){
        // 部门类型是销售 同步地点信息 其他的同步 部门信息
        if(dept.existDeptType(DeptEnum.RETAIL)){
            // 同步 地点信息 （先有地点信息 再有 门店信息）
            JSONObject synDDXX = new JSONObject();
            synDDXX.put("DDID",dept.getId());
            synDDXX.put("DDMC",dept.getName());
            synDDXX.put("GSID", dept.getCompany().getId());
            synDDXX.put("GSMC", dept.getCompany().getName());
            synDDXX.put("CKBJ", 1);
            synDDXX.put("MDBJ", 1);
            synDDXX.put("YXBJ", 1);
            synDDXX.put("TS01", DateUtils.format(new Date(), "yyyyMMdd.HHmmss.SSS"));
            synDDXX.put("LRR", "admin");
            synDDXX.put("LRRQ_SJ", DateUtils.format(new Date(), "yyyy-MM-dd HH:mm:ss"));
            synDDXX.put("CKJB", 2);
            synDDXX.put("WLSKBJ", 0);
            String DDtopic = "event:cm.branchEntry.synDDXX";
            Boolean DDflg = (Boolean) EventUtil.sendSynEvent(this, DDtopic, synDDXX).stream().findFirst().get();
            if (!DDflg){
                throw new RuntimeException("同步地点信息到旧框架时报错!");
            }
        } else {
            // 同步到旧框架 部门信息
            JSONObject synBMXX = new JSONObject();
            synBMXX.put("BMID",dept.getId());
            synBMXX.put("BMMC",dept.getName());
            synBMXX.put("TS01", DateUtils.format(Optional.ofNullable(dept.getLastUpdatedStamp()).orElse(new Date()), "yyyyMMdd.HHmmss.SSS"));
            synBMXX.put("LRR","admin");
            synBMXX.put("LRRQ_SJ", DateUtils.format(Optional.ofNullable(dept.getCreateDate()).orElse(new Date()),"yyyy-MM-dd HH:mm:ss"));
            String topic = "event:cm.branchEntry.synBMXX";
            Boolean flg = (Boolean) EventUtil.sendSynEvent(this, topic, synBMXX).stream().findFirst().get();
            if (!flg){
                throw new RuntimeException("同步部门信息到旧框架时报错!");
            }
        }
    }
    public String delete(SimpleRequest request) throws Exception  {
//        Dept dept = request.getO(Dept.class);
//        deptRepository.delete(dept);

        String id = request.get("id");
        long versions = (Long) request.get("version");

        Dept dept = deptRepository.findOne(id);
        if (dept == null) throw new RuntimeException("部门【" + id + "】在系统中不存在。");
        if (dept.getVersion() != versions) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        deptRepository.delete(dept);
        return "删除成功";
    }




    public Page<Dept> query(SimpleRequest request){
        List<Map> filters = request.get("condition");
        return deptRepository.findAll(JpaDsl.toCriteria(filters), PageRequest.of(request.get("page"), request.get("size")));
    }

    public Page<Dept> find(SimpleRequest request) throws Exception{
        return deptRepository.find( request.get("key"), PageRequest.of(request.get("page"), request.get("size")) );
    }

    public Dept findOne(String id) {
        return deptRepository.findOne(id);
    }

    /**
     * 查询部门开业时间
     * @param request
     * @return
     */
    public Dept findOpenDay(SimpleRequest request){
        Branch branch = request.getO("branch",Branch.class);
        List<Dept> deptList = deptRepository.findByBranch(branch);
        Dept dept = null;
        if(!deptList.isEmpty()){
            dept = deptList.get(0);
        }
        return dept;
    }

    public void synDept(Dept dept){
        // 同步 门店信息
        JSONObject synMDXX = new JSONObject();
        synMDXX.put("MDID",dept.getId());
        synMDXX.put("MDMC",dept.getName());
        synMDXX.put("GSID",dept.getCompany().getId());
        synMDXX.put("GSMC",dept.getCompany().getName());
        synMDXX.put("TS01", DateUtils.format(Optional.ofNullable(dept.getLastUpdatedStamp()).orElse(new Date()), "yyyyMMdd.HHmmss.SSS"));
        synMDXX.put("LRR","admin");
        synMDXX.put("LRRQ_SJ",Optional.ofNullable(dept.getCreateDate()).orElse(new Date()).toString());
        String topic = "event:cm.branchEntry.synMDXX";
        Boolean flg = (Boolean) EventUtil.sendSynEvent(this, topic, synMDXX).stream().findFirst().get();
        if (!flg){
            throw new RuntimeException("同步门店信息到旧框架时报错!");
        }
        // 同步 地点信息 （先有地点信息 再有 门店信息）
        JSONObject synDDXX = new JSONObject();
        synDDXX.put("DDID",dept.getId());
        synDDXX.put("DDMC",dept.getName());
        String DDtopic = "event:cm.branchEntry.synDDXX";
        Boolean DDflg = (Boolean) EventUtil.sendSynEvent(this, DDtopic, synDDXX).stream().findFirst().get();
        if (!DDflg){
            throw new RuntimeException("同步地点信息到旧框架时报错!");
        }
    }

    /**
     * 查询部门信息
     * @param request
     * @return
     */
    public List queryDeptAndBranch(SimpleRequest request){
        JSONObject jsonObject = request.getJO();
        String name = jsonObject.getString("key");
        if ("总部".equals(name)){
            List<Map<String, Object>> list = new ArrayList<>();
            Map<String, Object> map = new HashMap<>();
            map.put("ID","");
            map.put("NAME","总部");
            map.put("ADDRESS","广州市海珠区沥滘路号广州之窗总部大厦12层整层单元");
            map.put("DEPTID","");
            list.add(map);
            return list;
        }
        if (ObjectUtils.isEmpty(name)){
            return storeRepository.queryDeptAll();
        }
        return storeRepository.queryDeptByValue(name);
    }

    /**
     * App 模糊查询部门
     * @param request
     * @return
     */
    public List queryDept(SimpleRequest request){
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("key");
        return deptRepository.findLikeName(id);
    }

    /**
     * App 模糊查询部门
     * @param request
     * @return
     */
    public List queryDeptByDeptType(SimpleRequest request){
        JSONObject jsonObject = request.getJO();
        String id = jsonObject.getString("key");
        return deptRepository.findLikeNameAndDeptType(id);
    }


    /**
     * 通过部门获取成本中心
     */
    @FuncAlias(name = "getCostCenter")
    public DutyCenter getCostCenter(Dept dept) {
        DutyCenter costCenter = dept.getCostCenterId();
        if (costCenter == null) throw new RuntimeException("业务部门：" + dept.getName() + " 没有定义成本中心！");
        return costCenter;
    }

    /**
     * 通过部门获取利润中心
     */
    @FuncAlias(name = "getProfitCenter")
    public DutyCenter getProfitCenter(Dept dept) {
        DutyCenter profitCenter = dept.getProfitCenterId();
        if (profitCenter == null) throw new RuntimeException("业务部门：" + dept.getName() + " 没有定义成本中心！");
        return profitCenter;
    }

    public Dept findByAndBranchIdAndDeptTypeCode(SimpleRequest request) {
        String branchId = request.get("branch");
        Dept dept = deptRepository.findByAndBranchId(branchId);
        if (dept != null && dept.existDeptType(DeptEnum.SALE)) {
            return dept;
        }
        return null;
    }

    public List<Dept> findAllByCompany(SimpleRequest request) {
        String company = request.get("company");
        return deptRepository.findAllByCompany(company);
    }

    public List<Map> findDeptTypes(SimpleRequest request) {
        List<Map> result = new ArrayList<>();
        for (DeptEnum deptEnum : DeptEnum.values()){
            Map row = new HashMap();
            row.put("id", deptEnum.getDeptType());
            row.put("name", deptEnum.getMsg());
            result.add(row);
        }
        return result;
    }

}
